<script>
import { bdToGd } from '../../gis-map/js/translator.js';
import { getZzPeopleNewLocation } from '@gis/lib/api';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import PeopleIcon from '../assets/map_pop_bt_ren.png';
import Place from '../assets/map_pop_bt_gjweizhi.png';

const icon = {
  people: PeopleIcon,
  place: Place,
};

class TrackMarker {
  constructor(AMap, map, options) {
    const opt = {
      sec: 5,
      icon: null,
      iconWidth: '34px',
      iconHeight: '34px',
      iconOffset: [0, 0],
      labelOffset: [0, 0],
      labelColor: '#fff',
    };
    this.AMap = AMap;
    this.map = map;
    this.options = Object.assign(opt, options);
    this.marker = null;
    this.polyline = null;
  }
  getLngLat(data) {
    return bdToGd.apply(null, data ? data.lnglat || [] : []);
  }
  create(data) {
    const lnglat = this.getLngLat(data);
    const { icon, iconWidth, iconHeight, iconOffset, labelOffset, labelColor } = this.options;
    const marker = new this.AMap.Marker({
      map: this.map,
      anchor: 'center',
      extData: data,
      position: lnglat,
      content: `<div style="width: ${iconWidth};height: ${iconHeight};background: url(${icon}) center center / 100% 100% no-repeat;"></div>`,
      offset: new this.AMap.Pixel(...iconOffset),
      title: data.name,
      label: {
        content: `<div style="color: ${labelColor}">${data.label || ''}</div>`,
        direction: 'top',
        offset: new this.AMap.Pixel(...labelOffset),
      },
    });
    const polyline = new this.AMap.Polyline({
      map: this.map,
      path: [lnglat],
      strokeColor: data.color || '#22ddee',
      strokeStyle: 'solid',
      strokeWeight: 6,
      strokeOpacity: 0.3,
      showDir: true,
      extData: data,
    });
    this.marker = marker;
    this.polyline = polyline;
  }
  update(data) {
    const lnglat = new this.AMap.LngLat(...this.getLngLat(data));
    const distance = this.AMap.GeometryUtil.distance(lnglat, this.marker.getPosition());
    // console.log('distance: ', distance);
    if (distance > 0) {
      this.marker.moveTo(lnglat, (distance * 3.6) / this.options.sec);
      setTimeout(() => {
        const path = this.polyline.getPath();
        path.push(this.marker.getPosition());
        this.polyline.setPath(path);
        // console.log('polyline path: ', path);
      }, this.options.sec * 1000);
    }
  }
}

export default {
  name: 'people-markers',
  render() {
    return null;
  },
  props: {
    center: { type: Array, default: undefined },
  },
  async created() {
    this.AMap = this.$attrs.AMap;
    this.map = this.$attrs.map;
    this.sec = 5;
    this.peoples = {};
    this.$watch(
      () => this.center,
      (center) => {
        if (!center || !Array.isArray(center)) return;
        const [lng, lat] = this.center;
        if (lng && lat) {
          this.createWarnPlace(lng, lat);
        }
      },
      { immediate: true }
    );
    await this.getDataAsync().catch(() => {});
    this.polling();
  },
  unmounted() {
    clearTimeout(this.pollingTimer);
    this.polling = null;
    this.getDataAsync = null;
    this.map = null;
  },
  methods: {
    createWarnPlace(lng, lat) {
      const lnglat = bdToGd(lng, lat);
      if (this.centerMarker) {
        this.centerMarker.setPosition(new this.AMap.LngLat(...lnglat));
        return;
      }
      const marker = new this.AMap.Marker({
        map: this.map,
        anchor: 'bottom-center',
        position: lnglat,
        content: `<div style="width: 40px;height: 46px;background: url(${icon.place}) center center no-repeat;background-size: 100% 100%"></div>`,
        // offset: new this.AMap.Pixel(0, -23),
        offset: new this.AMap.Pixel(0, 0),
        title: '告警位置',
        label: {
          content: `<div style="color: #f14c25">告警位置</div>`,
          direction: 'top',
          offset: new this.AMap.Pixel(0, 0),
        },
      });
      // this.map.setZoomAndCenter(14, new this.AMap.LngLat(lng, lat));
      this.map.setFitView(marker);
      this.centerMarker = marker;
    },
    createPeople(data) {
      // console.log(data.id);
      if (!data || !data.id) {
        return;
      }
      if (this.peoples[data.id]) {
        this.peoples[data.id].update(data);
        // console.log('update: ', data.id);
      } else {
        this.peoples[data.id] = new TrackMarker(this.AMap, this.map, {
          icon: icon.people,
          sec: this.sec,
        });
        this.peoples[data.id].create(data);
        // console.log('create: ', data.id);
      }
      // console.log(this.peoples);
    },
    async getDataAsync() {
      const { area_code } = useUserInfoStore();
      const params = {
        area_code: area_code,
      };
      const res = await getZzPeopleNewLocation(params).catch(() => {});
      const data = this.handleCommonResult(res);
      data.forEach((item) => {
        // if (this.dataSource) {
        //   return;
        // }
        if (item && item.id && item.online == 1 && item.longitude && item.latitude) {
          item.lnglat = [item.longitude, item.latitude];
          item.label = item.type_name + '：' + item.name;
          this.createPeople(item);
        }
        // this.dataSource = data.map((o) => ({
        //   ...o,
        //   id: item.id,
        //   label: item.label,
        //   lnglat: [o.longitude, o.latitude],
        // }));
        // console.log('dataSource: ', this.dataSource);
      });
    },
    polling() {
      clearTimeout(this.pollingTimer);
      this.pollingTimer = setTimeout(async () => {
        await this.getDataAsync().catch(() => {});
        this.polling();
      }, this.sec * 1000);
    },
  },
};
</script>

<style scoped lang="less"></style>
